package org.example.common.security.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.common.core.constants.HttpStatus;
import org.example.common.core.domain.model.LoginUser;
import org.example.common.redis.utils.LoginHelper;
import org.example.common.security.annotation.PreAuthorize;
import org.example.common.security.exception.PreAuthorizeException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 自定义权限实现
 *
 */
@Aspect
@Component
public class PreAuthorizeAspect
{
    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    /** 数组为0时 */
    private static final Integer ARRAY_EMPTY = 0;

    @Around("@annotation(preAuthorize)")
    public Object around(ProceedingJoinPoint point, PreAuthorize preAuthorize) throws Throwable
    {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (ObjectUtils.isEmpty(preAuthorize))
        {
            return point.proceed();
        }
        if (!StringUtils.isEmpty(preAuthorize.hasPermi()))
        {
            if(ARRAY_EMPTY < preAuthorize.andRoles().length){
                if (hasPermi(preAuthorize.hasPermi())&& hasAnyRoles(preAuthorize.andRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});
            }else if(ARRAY_EMPTY < preAuthorize.orRoles().length){
                if (hasPermi(preAuthorize.hasPermi())|| hasAnyRoles(preAuthorize.orRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});

            }else{
                if (hasPermi(preAuthorize.hasPermi()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});
            }
        }
        else if (!StringUtils.isEmpty(preAuthorize.lacksPermi()))
        {
            if(ARRAY_EMPTY < preAuthorize.andRoles().length){
                if (lacksPermi(preAuthorize.lacksPermi())&& hasAnyRoles(preAuthorize.andRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});
            }else if(ARRAY_EMPTY < preAuthorize.orRoles().length){
                if (lacksPermi(preAuthorize.lacksPermi())|| hasAnyRoles(preAuthorize.orRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});

            }else{
                if (lacksPermi(preAuthorize.lacksPermi()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.lacksPermi()});
            }
        }
        else if (ARRAY_EMPTY < preAuthorize.hasAnyPermi().length)
        {
            if(ARRAY_EMPTY < preAuthorize.andRoles().length){
                if (hasAnyPermi(preAuthorize.hasAnyPermi())&& hasAnyRoles(preAuthorize.andRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});
            }else if(ARRAY_EMPTY < preAuthorize.orRoles().length){
                if (hasAnyPermi(preAuthorize.hasAnyPermi())|| hasAnyRoles(preAuthorize.orRoles()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,new String[]{preAuthorize.hasPermi()});
            }else{
                if (hasAnyPermi(preAuthorize.hasAnyPermi()))
                {
                    return point.proceed();
                }
                throw new PreAuthorizeException(HttpStatus.ERROR,preAuthorize.hasAnyPermi());
            }
        }
        return point.proceed();
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorizes()))
        {
            return false;
        }
        return hasPermissions(loginUser.getAuthorizes(), permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermi(String permission)
    {
        return hasPermi(permission) != true;
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermi(String[] permissions)
    {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorizes()))
        {
            return false;
        }
        Collection<String> authorities = loginUser.getAuthorizes();
        for (String permission : permissions)
        {
            if (permission != null && hasPermissions(authorities, permission))
            {
                return true;
            }
        }
        return  false;
    }
    /**
     * 判断是否包含权限
     *
     * @param authorities 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Collection<String> authorities, String permission)
    {
        return authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
    }



    /**
     * 判断用户是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasRole(String role)
    {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getRoles()))
        {
            return false;
        }
        for (String roleKey : loginUser.getRoles())
        {
            if (loginUser.isSuperAdmin()
                    || roleKey.equals(role))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证用户是否具有以下任意一个角色
     *
     * @param roles 角色列表
     * @return 用户是否具有以下任意一个角色
     */
    public boolean hasAnyRoles(String[] roles)
    {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getRoles()))
        {
            return false;
        }
        for (String role : roles)
        {
            if (hasRole(role))
            {
                return true;
            }
        }
        return false;
    }
}
